    //
    //  SearchViewController.m
    //  quxiangtao
    //
    //  Created by xbmios on 2018/8/2.
    //  Copyright © 2018年 shanhaijin. All rights reserved.
    //

#import "SearchViewController.h"
#import "SearchResultModel.h"
#import "SearchTableViewCell.h"
#import "UIViewController+JTNavigationExtension.h"
#import "SupprotSearchTableViewCell.h"
#import "ShoppingGoodsContentViewController.h"
#import "HistorySearchView.h"
#import "DY_searchHistoryDataBase.h"
#import "UIButton+Extension.h"
#import "XTPopView.h"
#import "UploadShopImageController.h"

static NSString *searchCellID = @"searchCellID";
static NSString *supportCellID = @"supportCellID";

@interface SearchViewController ()<selectIndexPathDelegate,UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
{
    
    CGPoint animationPoint;
}

@property (strong, nonatomic) UITableView *searchResultTableview;

@property (strong, nonatomic) UITextField *searchTextField;

@property (strong, nonatomic) UIImageView *categoryV;
@property (strong, nonatomic) UIView *btnsView;

@property (strong, nonatomic) UIView *sliderLine;

@property (strong, nonatomic) UILabel *logoL;

@property (strong, nonatomic) NSMutableArray *categoryArrM;

@property (strong, nonatomic) NSArray *array;

@property (strong, nonatomic) NSMutableArray *btnArr;
@property (strong, nonatomic) NSMutableArray *labelArr;

@property (copy, nonatomic) NSString *logoHistoryL;

@property (strong, nonatomic) UIButton *confirmBtn;

@property (strong, nonatomic) NSMutableArray *searchResultArr;

@property (assign, nonatomic) NSInteger page;

@property (assign, nonatomic) NSInteger searchType;

@property (weak, nonatomic) UIButton *chooseButton;

@property (strong, nonatomic) UIButton *selectedBtn;
// 用于标记在价格是选中状态下，显示不同的图片  YES 表示价格升序  NO表示价格降序
@property (assign, nonatomic) BOOL priceIsSelected;

@property (copy, nonatomic) NSString *sort_Id;

@property (nonatomic, strong) NSMutableArray *historyArray;

@property (nonatomic, weak) HistorySearchView *searchTable;

@end

@implementation SearchViewController

- (NSMutableArray *)historyArray {
    if (!_historyArray) {
        _historyArray = [[NSMutableArray alloc] initWithArray:[[DY_searchHistoryDataBase shareDataBase] readLocalArray]];
    }
    return _historyArray;
}

/**添加历史记录*/
- (void)addHistoryWithString:(NSString *)string {
    self.searchTable.hidden = YES;
    if ([self.historyArray containsObject:string]) {
        [self.historyArray removeObject:string];
    }
    [self.historyArray insertObject:string atIndex:0];
    if (self.historyArray.count > 10) {
        [self.historyArray removeObjectAtIndex:10];
    }
    self.searchTable.dataArray = self.historyArray;
    [[DY_searchHistoryDataBase shareDataBase] writeLocalWithDataArray:self.historyArray];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = WhiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.page = 1;
    
    if (self.categoryType == 1 || self.categoryType == 2) {
        // 淘宝、天猫
        self.searchType = 1;
    }else if (self.categoryType == 0) {
        // 自营
        self.searchType = 2;
    }
   
    [self createSearchView];
    
    [self.view addSubview:self.searchResultTableview];
    __weak typeof(self) weakSelf = self;
    [self.searchResultTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(Height_StatusBar + 44);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
    }];
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载。。。。" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据！" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = Font(17);
    footer.stateLabel.textColor = Color999999;
    self.searchResultTableview.mj_footer = footer;
    self.searchResultTableview.mj_footer.hidden = NO;
    
    HistorySearchView *historyView = [[HistorySearchView alloc] initWithFrame:CGRectMake(0, Height_StatusBar+44, SCREEN_WIDTH, SCREEN_HEIGHT)];
    historyView.deleteIndexBlock = ^{
        [weakSelf.historyArray removeAllObjects];
    };
    [self.view addSubview:historyView];
    self.searchTable = historyView;
    self.searchTable.dataArray = self.historyArray;
    
    self.searchTable.searchIndexBlock = ^(NSString * _Nonnull cellString) {
        weakSelf.searchTable.hidden = YES;
        
        weakSelf.searchTextField.text = cellString;
        if (weakSelf.searchTextField.text.length < 1) {
            [[KYAlertView sharedInstance] showAlertViewWithMessage:@"请输入搜索内容"];
            return;
        }
        [weakSelf addHistoryWithString:weakSelf.searchTextField.text];
        [weakSelf.view endEditing:YES];
        [weakSelf.searchTextField resignFirstResponder];
        [weakSelf.searchResultArr removeAllObjects];
        [weakSelf.searchResultTableview reloadData];
        [weakSelf loadSearchResult];
    };
    
    [self loadHotSearch];
    
    UIButton *woxiangyaoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [woxiangyaoButton setImage:[UIImage imageNamed:@"woxiangyao"] forState:UIControlStateNormal];
    [self.view addSubview:woxiangyaoButton];
    [woxiangyaoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(jisuan(130), jisuan(60)));
        make.right.mas_equalTo(-10);
    }];
    [woxiangyaoButton addTarget:self action:@selector(woxiangyaoClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)woxiangyaoClick {
    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        return;
    }
    [self.navigationController pushViewController:[[UploadShopImageController alloc] init] animated:YES];

}

- (void)createSearchView {
    
    UIView *searchView = [[UIView alloc] init];
    searchView.backgroundColor = WhiteColor;
    [self.view addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(Height_StatusBar);
        make.height.mas_equalTo(44);
    }];
    
    UIButton *confirmBtn = [[UIButton alloc] init];
    [confirmBtn setTitle:@"取消" forState:UIControlStateNormal];
    [confirmBtn setTitle:@"取消" forState:UIControlStateSelected];
    confirmBtn.titleLabel.font = Font(30);
    [confirmBtn setTitleColor:Colorff0000 forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchView.mas_centerY);
        make.right.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(60, 44));
    }];
    
    UIView *searchTbg = [[UIView alloc] init];
    searchTbg.backgroundColor = Colorefefef;
    [searchView addSubview:searchTbg];
    [searchTbg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.equalTo(confirmBtn.mas_left);
        make.centerY.equalTo(searchView.mas_centerY);
        make.height.mas_equalTo(30);
    }];
    MKViewBorderRadius(searchTbg, 15, 0, Colorefefef);
    
    UIImageView *searchImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"serchimage"]];
    [searchTbg addSubview:searchImage];
    [searchImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.mas_equalTo(searchTbg.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(jisuan(36), jisuan(36)));
    }];

    UIButton *chooseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [chooseButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    chooseButton.backgroundColor = Colorff0000;
    chooseButton.titleLabel.font = [UIFont systemFontOfSize:jisuan(28)];
    [chooseButton setImage:[UIImage imageNamed:@"priceArrowbg"] forState:UIControlStateNormal];
    [chooseButton addTarget:self action:@selector(choseButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [searchTbg addSubview:chooseButton];
    [chooseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 24));
        make.centerY.mas_equalTo(searchTbg.mas_centerY);
        make.right.mas_equalTo(-3);
    }];
    MKViewBorderRadius(chooseButton, 12, 0, WhiteColor);
    if (self.searchType == 1) {
        [chooseButton setTitle:@"淘宝" forState:UIControlStateNormal];
    } else if (self.searchType == 2) {
        [chooseButton setTitle:@"自营" forState:UIControlStateNormal];
    } else {
        [chooseButton setTitle:@"京东" forState:UIControlStateNormal];
    }
    [chooseButton layoutButtonWithImageStyle:ZJButtonImageStyleRight imageTitleToSpace:5];
   
    self.chooseButton = chooseButton;
    
    self.searchTextField = [[UITextField alloc] init];
    self.searchTextField.placeholder = @"全网搜索";
    self.searchTextField.returnKeyType =  UIReturnKeySearch;
    [self.searchTextField becomeFirstResponder];
    self.searchTextField.delegate = self;
    self.searchTextField.tintColor= Colorff0000;
    self.searchTextField.font = [UIFont systemFontOfSize:15];
    [self.searchTextField setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [searchTbg addSubview:self.searchTextField];
    [self.searchTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchImage.mas_right).offset(5);
        make.top.bottom.mas_equalTo(0);
        make.right.equalTo(chooseButton.mas_left).offset(-2);
    }];
    
    [self createWithtitle:@"综合" image:nil withTag:0];
    [self createWithtitle:@"销量" image:nil withTag:1];
    [self createWithtitle:@"价格" image:[UIImage imageNamed:@"priceNormal"] withTag:2];
    [self createWithtitle:@"优惠" image:nil withTag:3];
}

- (void)choseButtonClick:(UIButton *)sender {
    CGPoint point = CGPointMake(WIDTH-113,Height_StatusBar+43);
    XTPopView *menu = [[XTPopView alloc] initWithOrigin:point Width:70 Height:30*2 Type:XTTypeOfUpLeft Color:[[UIColor blackColor] colorWithAlphaComponent:0.6]];
    menu.dataArray = @[@"淘宝", @"自营"];
    menu.fontSize = 13;
    menu.row_height = 30;
    menu.titleTextColor = [UIColor whiteColor];
    menu.delegate = self;
    [menu popView];
}

- (void)selectIndexPathRow:(NSInteger)index
{
    NSArray *chouse = @[@"淘宝", @"自营"];
    [self.chooseButton setTitle:chouse[index] forState:UIControlStateNormal];
    self.searchType = index + 1;
    if (self.searchTextField.text.length  > 0) {
        self.page = 1;
        [self.searchResultArr removeAllObjects];
        [self.searchResultTableview reloadData];
        [self loadSearchResult];
    } else {
        [self.searchTextField becomeFirstResponder];
    }
    
}

- (void)loadHotSearch {
    NSMutableArray *mutarray = [[NSMutableArray alloc] init];
    WS(weakSelf);
    [PPNetworkHelper POST:@"search/Index/hotsearch" parameters:nil success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 1) {
            NSArray *array = responseObject[@"data"];
            for (NSDictionary *dic in array) {
                [mutarray addObject:[NSString stringWithFormat:@"%@",dic[@"content"]]];
            }
            weakSelf.searchTable.sectionArray = mutarray;
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)createWithtitle:(NSString *)name image:(UIImage *)image withTag:(NSInteger)tag {
    
    UIButton *btn = [[UIButton alloc] init];
    btn.titleLabel.font = Font(24);
    btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [btn setTitle:name forState:UIControlStateNormal];
    [btn setTitleColor:Color333333 forState:UIControlStateNormal];
    [btn setTitleColor:Colorff0000 forState:UIControlStateSelected];
    
    btn.tag = tag;
    CGFloat width = jisuan(80);
    CGFloat margin = (WIDTH - SmallMargin * 2 - Margin * 2 - width * 4) / 3.0;
    CGFloat x = BigMargin + (width + margin) * tag;
    btn.frame = CGRectMake(x, Height_StatusBar+44, width, jisuan(60));
    [self.view addSubview:btn];
    
    if (image) {
        
        [btn setImage:image forState:UIControlStateNormal];
    }
    
    if (tag == 0) {
        
        // 设置“综合”为默认选中状态
        btn.selected = YES;
        self.selectedBtn = btn;
    }else {
        btn.selected = NO;
    }
    
    
    if (tag == 0) {
        
        // 综合
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
    }else if (tag == 3) {
        
        // 筛选
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.imageView.frame.size.width - btn.frame.size.width + btn.titleLabel.frame.size.width + jisuan(15), 0, 0);
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -btn.titleLabel.frame.size.width - btn.frame.size.width +  jisuan(20));
        
    }else if (tag == 2) {
        // 价格
        
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.imageView.frame.size.width - btn.frame.size.width + btn.titleLabel.frame.size.width + jisuan(15), 0, 0);
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -btn.titleLabel.frame.size.width - btn.frame.size.width + jisuan(20));
        
    }
    
    
    if (tag == 2) {
        
        // 价格
        [btn setImage:[UIImage imageNamed:@"priceUp"] forState:UIControlStateSelected];
        
    }else if (tag == 3) {
        
        // 筛选
    
    }
    
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark -分类、综合按钮的点击
- (void)btnClick:(UIButton *)btn {
    
    if (btn!= self.selectedBtn) {
        
        self.selectedBtn.selected = NO;
        btn.selected = YES;
        self.selectedBtn = btn;
        
    }else{
        
        self.selectedBtn.selected = YES;
        
    }
    
    if (btn.tag == 0) {
        
        NSLog(@"综合");
        self.priceIsSelected = YES;
        self.sort_Id = @"1";
        // 综合数据请求
        
    }else if (btn.tag == 1) {
        
        NSLog(@"销量");
        self.priceIsSelected = YES;
        self.sort_Id = @"2";
        // 销量数据请求
        
    }else if (btn.tag == 2) {
        
        if (self.priceIsSelected) {
            
            NSLog(@"升序");
            
            [btn setImage:[UIImage imageNamed:@"priceUp"] forState:UIControlStateSelected];
            
            self.priceIsSelected = NO;
            self.sort_Id = @"3";
            // 价格升序数据请求
            
            
        }else {
            
            NSLog(@"降序");
            
            [btn setImage:[UIImage imageNamed:@"priceDown"] forState:UIControlStateSelected];
            
            self.priceIsSelected = YES;
            self.sort_Id = @"4";
            // 价格降序数据请求
        }
        
    }else  {
        
        NSLog(@"筛选");
        self.priceIsSelected = YES;
        self.sort_Id = @"5";
        // 筛选数据请求
        
    }
    self.page = 1;
    [self loadSearchResult];
}


- (void)loadNewData{
    
    [self.searchResultTableview.mj_footer resetNoMoreData];
    
    self.page = 1;
    [self loadSearchResult];
    
    // 刷新表格
    [self.searchResultTableview reloadData];
    
    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.searchResultTableview.mj_header endRefreshing];
    
}

- (void)loadMoreData{
    
    self.page++;
    [self loadSearchResult];
    
    // 刷新表格
    [self.searchResultTableview reloadData];
    
    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.searchResultTableview.mj_footer endRefreshing];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (self.searchTextField.text.length < 1) {
        [[KYAlertView sharedInstance] showAlertViewWithMessage:@"请输入搜索内容"];
        return YES;
    }
    
    [self addHistoryWithString:self.searchTextField.text];
    [self.view endEditing:YES];
    [self.searchTextField resignFirstResponder];
    [self.searchResultArr removeAllObjects];
    [self.searchResultTableview reloadData];
    [self loadSearchResult];
    return YES;
}


#pragma mark -取消点击
- (void)confirmClick{
    [self.navigationController popViewControllerAnimated:NO];
}


- (void) updataLayout {
    
    [self.searchResultTableview mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(Height_StatusBar+44+jisuan(60));
    }];
    
}

#pragma mark -搜索接口
- (void)loadSearchResult {
    
    __weak typeof(self) weakSelf = self;
    [SearchResultModel searchResultModelWithPage:self.page andType:self.searchType searchText:self.searchTextField.text sort_Id:self.sort_Id  successBlock:^(id responseObject) {
            NSArray *arr = responseObject[@"map_data"];
            if (arr.count > 0 || weakSelf.searchResultArr.count > 0 ) {
                [self updataLayout];
                weakSelf.searchResultTableview.hidden = NO;
                if (self.page == 1) {
                    weakSelf.searchResultArr = (NSMutableArray *)arr;
                }else {
                    [weakSelf.searchResultArr addObjectsFromArray:arr];
                }
                [weakSelf.searchResultTableview reloadData];
                if (self.page > 1 && arr.count == 0) {
                    [self.searchResultTableview.mj_footer endRefreshingWithNoMoreData];
                }
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:(self.page - 1) * 10];
                [weakSelf.searchResultTableview selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            }else {
                weakSelf.searchResultTableview.hidden = YES;
            }
    } failBlock:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        return jisuan(205);
}

#pragma mark -delegate \ DATASOURCE
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.searchResultArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.searchType == 1) {
        
        SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchCellID forIndexPath:indexPath];
        // 淘宝、天猫
        cell.searchModel = self.searchResultArr[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    }else if (self.searchType == 2) {
        
        SupprotSearchTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:supportCellID forIndexPath:indexPath];
        // 趣享淘
        cell1.searchModel = self.searchResultArr[indexPath.row];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell1;
        
    }else {
        
        // 京东
        
        return nil;
        
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.searchType == 1) {
        // 淘宝、天猫 搜索
        SearchResultModel *model = self.searchResultArr[indexPath.row];
        
        [[CommonAction sharedInstance] goToTbGoodsDetailWith:self itemDetailPage:model.coupon_share_url];
   
    }else if (self.searchType == 2){
        
        // 自营
        ShoppingGoodsContentViewController *vc = [[ShoppingGoodsContentViewController alloc] init];
        SearchResultModel *model = self.searchResultArr[indexPath.row];
        vc.goodID = model.id;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        
        // 京东
        
    }
    
}



- (void)textFieldChanged:(UITextField*)textField{
    if (textField.text.length < 1) {
        self.searchTable.hidden = NO;
    }
}



#pragma mark -lazy
- (UITableView *)searchResultTableview {

    if (!_searchResultTableview) {

        _searchResultTableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _searchResultTableview.delegate = self;
        _searchResultTableview.dataSource = self;
        _searchResultTableview.showsVerticalScrollIndicator = NO;
        _searchResultTableview.showsHorizontalScrollIndicator = NO;
        _searchResultTableview.estimatedRowHeight = 0;
        _searchResultTableview.estimatedSectionHeaderHeight = 0;
        _searchResultTableview.estimatedSectionFooterHeight = 0;
        _searchResultTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_searchResultTableview registerClass:[SearchTableViewCell class] forCellReuseIdentifier:searchCellID];
        [_searchResultTableview registerClass:[SupprotSearchTableViewCell class] forCellReuseIdentifier:supportCellID];

        if (@available(iOS 11.0, *)) {
            _searchResultTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }

    return _searchResultTableview;

}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [TalkingData trackPageBegin:@"搜索页"];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [self.searchTextField resignFirstResponder];
    [TalkingData trackPageEnd:@"搜索页"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
